/*
 *
 *  Copyright 2015-2016 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */

package com.zwl.swagger.plugins;

import com.zwl.swagger.CommentContainer;
import com.zwl.swagger.comment.MethodComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

/**
 * 接口描述，方法上的注释
 * @author zhangweilin
 * @Description:
 * @date 2021年08月20日 20:59
 */
@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER)
@Slf4j
public class OperationSummaryReaderPlus implements OperationBuilderPlugin, ContextDescriper {
	private final DescriptionResolver descriptions;

	@Autowired
	CommentContainer commentContainer;

	@Autowired
	public OperationSummaryReaderPlus(DescriptionResolver descriptions) {
		this.descriptions = descriptions;
	}

	@Override
	public void apply(OperationContext context) {

		String description = "";
		try {
			description = getMethodDescription(context);
			MethodComment methodComment = commentContainer.getMethodCommentMap().get(description);
			if (null != methodComment) {
				String comment = methodComment.getComment();
				if (!StringUtils.isEmpty(comment)) {
					String summary = comment.replaceAll("\\s.*", "");
					if (!StringUtils.isEmpty(summary)) {
						context.operationBuilder().summary(summary);
					}
				}
			}
		} catch (Exception e) {
			log.error("OperationSummaryReaderPlus异常,description: " + description,e);
		}
	}

	@Override
	public boolean supports(DocumentationType delimiter) {
		return SwaggerPluginSupport.pluginDoesApply(delimiter);
	}
}
